package com.znyj.servlet.secondaryController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.znyj.servlet.aes.AesException;
import com.znyj.servlet.entity.TaskEntity;
import com.znyj.servlet.service.ReportService;
import com.znyj.servlet.service.TaskService;
import com.znyj.servlet.thrift.ThriftClient;
import com.znyj.servlet.utilsTool.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/demo")
public class DemoController {
    private static final Logger logger = LoggerFactory.getLogger(DemoController.class);

    @Resource
    private ReportService reportService;

    @Resource
    private TaskService taskService;

    @RequestMapping(value = "/{device_id}", method = RequestMethod.GET)
    protected String singlePage(@PathVariable(value = "device_id") String device_id, HttpServletRequest request) throws ParseException, IOException, AesException, InterruptedException {
        Map<String, Object> model = new HashMap<String, Object>();

        JSONObject requestJson = new JSONObject(true);
        requestJson.put("userId","demo");
        requestJson.put("deviceId",device_id);
        requestJson.put("userLocation","null");
        Timestamp time = new Timestamp(System.currentTimeMillis());
        requestJson.put("timestamp", time.getTime());

        //String status = ThriftClient.getRealTimeDeviceInfo(device_id);
        String temp= HttpClientUtil.getDeviceInfoApi(requestJson);
        JSONObject responseJson = JSON.parseObject(temp);

        model.put("deviceId", responseJson.getString("deviceId"));
        model.put("onlineStatus", responseJson.getString("onlineStatus"));
        model.put("statusA", responseJson.getLong("statusA"));
        model.put("statusB", responseJson.getLong("statusB"));
        model.put("orderCreateTimeA", responseJson.getLong("orderCreateTimeA"));
        model.put("orderCreateTimeB", responseJson.getLong("orderCreateTimeB"));
        model.put("orderDurationSecA", responseJson.getLong("orderDurationSecA"));
        model.put("orderDurationSecB", responseJson.getLong("orderDurationSecB"));
        model.put("sigQuality", responseJson.getLong("sigQuality"));
        model.put("batteryLeftTime", responseJson.getLong("batteryLeftTime"));//分钟
        model.put("errorInfo", responseJson.getString("errorInfo"));
        model.put("userIdA", responseJson.getString("userIdA"));
        model.put("userIdB", responseJson.getString("userIdB"));
        model.put("orderIdA", responseJson.getLong("orderIdA"));
        model.put("orderIdB", responseJson.getLong("orderIdB"));
        model.put("merchantName", responseJson.getString("merchantName"));
        model.put("merchantAddress", responseJson.getString("merchantAddress"));
        model.put("poiid", responseJson.getString("poiid"));

        if(responseJson.getLong("orderIdA")==0) {
            model.put("leftSec", -1);
            model.put("totalSec", -1);
        }else{
            Date d1 = new Date();
            long left = responseJson.getLong("orderDurationSecA") * 1000 - d1.getTime() + responseJson.getLong("orderCreateTimeA");
            long left_sec = left / (1000);
            model.put("leftSec", left_sec);
            model.put("totalSec", responseJson.getLong("orderDurationSecA"));
        }
        request.setAttribute("model", model);
        return "/demo_page";
    }

    @RequestMapping(value = "/ctrl.inner", method = RequestMethod.POST)
    protected
    @ResponseBody
    String ctrlInner(@RequestBody String receiveData, HttpSession session) throws ParseException, IOException, InterruptedException, AesException {
        JSONObject getJson = JSON.parseObject(receiveData);
        int actionMsg = getJson.getInteger("actionMsg");
        String deviceId = getJson.getString("deviceId");
        int delay = 10;

        JSONObject requestJson = new JSONObject();
        Timestamp time = new Timestamp(System.currentTimeMillis());
        requestJson.put("deviceId", deviceId);
        requestJson.put("port", 2);
        requestJson.put("userId", HttpClientUtil.getRandomString(8)+"demo");
        requestJson.put("userLocation", "0,0");
        requestJson.put("createTime", time.getTime());
        requestJson.put("durationSec", delay * 60);
        requestJson.put("actionMsg", actionMsg);
        requestJson.put("controlMsg", "");

        String temp= HttpClientUtil.openDeviceApi(requestJson);
        JSONObject responseJson = JSON.parseObject(temp);
        //处理消息

        return responseJson.toString();
    }

    @RequestMapping(value = "/result.inner", method = RequestMethod.POST)
    protected
    @ResponseBody
    String result(@RequestBody String receiveData, HttpSession session) throws ParseException, IOException, InterruptedException, AesException {
        JSONObject getJson = JSON.parseObject(receiveData);
        long orderId = getJson.getLong("orderId");

        String temp= HttpClientUtil.getOrderInfoApi(orderId);
        JSONObject responseJson = JSON.parseObject(temp);
        //处理消息

        return responseJson.toString();
    }
//    @RequestMapping(value = "/gettime.inner", method = RequestMethod.POST)
//    protected
//    @ResponseBody
//    String getTime(@RequestBody String receiveData) throws ParseException, IOException {
//        JSONObject getJson = JSON.parseObject(receiveData);
//        JSONObject putJson = new JSONObject();
//        String deviceId = getJson.getString("deviceId");
//
//        TaskEntity taskEntity = taskService.findLast(deviceId);
//        if (taskEntity.getControlMsg().indexOf("close") != -1) {
//            putJson.put("left_sec", -1);
//            putJson.put("total_sec", taskEntity.getDurationSec());
//        } else {
//            if (taskEntity.getSendStatus() == 1) {
//                Date d1 = new Date();
//                long temp = taskEntity.getDurationSec() * 1000 - d1.getTime() + taskEntity.getCreateTime().getTime();
//                long left_sec = temp / (1000);
//                putJson.put("left_sec", left_sec);
//                putJson.put("total_sec", taskEntity.getDurationSec());
//            } else {
//                putJson.put("left_sec", -1);
//                putJson.put("total_sec", taskEntity.getDurationSec());
//            }
//        }
//        return putJson.toString();
//    }

//    @RequestMapping(value = "/ctrl.inner", method = RequestMethod.POST)
//    protected
//    @ResponseBody
//    String ctrlInner(@RequestBody String receiveData, HttpSession session) throws ParseException, IOException {
//        JSONObject getJson = JSON.parseObject(receiveData);
//        JSONObject putJson = new JSONObject();
//
//        String click = getJson.getString("click");
//        String deviceId = getJson.getString("deviceId");
//        int which = (getJson.getInteger("which"));
//        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//
//
//        String userId = "demo";
//
//        switch (which) {
//            case 0: {
//                if (click.equals("open")) {
//                    logger.info("thrift demo open all");
//                    putJson = ThriftClient.taskSendThriftApi(userId, deviceId, timestamp.getTime(), 180, "cdbopen", "null");
//                } else if (click.equals("close")) {
//                    logger.info("thrift demo close all");
//                    putJson = ThriftClient.taskSendThriftApi(userId, deviceId, timestamp.getTime(), 0, "cdbclose", "null");
//                }
//                break;
//            }
//
//            case 1: {
//                if (click.equals("open"))
//                    putJson = ThriftClient.taskSendThriftApi(userId, deviceId, timestamp.getTime(), 1800, "cdbaopen", "null");
//                else if (click.equals("close")) {
//                    putJson = ThriftClient.taskSendThriftApi(userId, deviceId, timestamp.getTime(), 0, "cdbaclose", "null");
//                }
//                break;
//            }
//
//            case 2: {
//                if (click.equals("open"))
//                    putJson = ThriftClient.taskSendThriftApi(userId, deviceId, timestamp.getTime(), 900, "cdbbopen", "null");
//                else if (click.equals("close")) {
//                    putJson = ThriftClient.taskSendThriftApi(userId, deviceId, timestamp.getTime(), 0, "cdbbclose", "null");
//                }
//                break;
//            }
//        }
//        return putJson.toString();
//    }
}
